<template>
  <q-page>
    <q-inner-loading visible v-if="model.id==0">
      <q-spinner-gears size="50px" color="primary"></q-spinner-gears>
      <b class="text-primary">数据加载中...</b>
    </q-inner-loading>

    <!-- header -->
    <q-card v-if="model.id>0">
      <q-card-main class="row gutter-x-sm q-pa-sm movie-header q-mb-sm">
        <div class="col-auto" v-if="model.poster">
          <img style="height:80px;" :src="model.poster" />
        </div>
        <div class="col">
          <div class="q-card-title row">
            <div class="col">{{model.name}} <small> ({{model.releaseDate}}上映)</small></div>
            <q-btn class="col-auto" flat round dense icon="mdi-settings" color="primary"
                @click="toggleSetting(true)" />
          </div>
          <!-- main info -->
          <div class="row gutter-x-sm q-card-subtitle text-right">
            <!-- score -->
            <div class="col text-left" v-if="model.score>0">
              <div><b class="text-primary"><big>{{(score/10).toFixed(3)}}</big></b>分</div>
              <small>豆瓣：{{(model.score/10).toFixed(1)}}分<span v-if="model.stars>0">/{{(model.stars/10).toFixed(1)}}档</span></small>
            </div>
            <div class="col text-left" v-if="model.score<=0 && isAdmin">
              <div v-if="model.predict>0">预测：<b class="text-primary"><big>{{(model.predict/10).toFixed(1)}}</big></b> 分</div>
              <small v-if="model.predictV4Count>0">V2：
                <b>{{(model.predictV4/10).toFixed(1)}}</b>分 | {{model.predictV4Count}}人
              </small>
              &nbsp;&nbsp;&nbsp;&nbsp;
              <small v-if="model.predictV3>0">V3：<b>{{(model.predictV3/10).toFixed(1)}}</b>分</small>
              <div v-if="model.predict<=0">暂无预测分数</div>
            </div>
            <!-- counts list -->
            <div class="col-auto">
              <div><b>{{model.ratingCount}}</b>人</div>
              <div>评分</div>
            </div>
            <div class="col-auto">
              <div><b>{{model.wishCount}}</b>人</div>
              <div>想看</div>
            </div>
            <div class="col-auto mobile-hide">
              <div><b>{{model.commentCount}}</b>条</div>
              <div>短评</div>
            </div>
            <div class="col-auto mobile-hide">
              <div><b>{{model.reviewCount}}</b>条</div>
              <div>影评</div>
            </div>
          </div>
        </div>
        <q-collapsible class="col-12 score-target" v-if="exactScore>0">
          <template slot="header">
            <q-item-side left>
              <small>距离 <b>{{(scoreTarget(1)/10).toFixed(1)}}</b> 分还需：</small>
            </q-item-side>
            <q-item-main><small>{{scoreDetail(1)}}</small></q-item-main>
          </template>
          <q-item>
            <q-item-side left>
              <small>距离 <b>{{(scoreTarget(2)/10).toFixed(1)}}</b> 分还需：</small>
            </q-item-side>
            <q-item-main><small>{{scoreDetail(2)}}</small></q-item-main>
          </q-item>
          <q-item>
            <q-item-side left>
              <small>距离 <b>{{(scoreTarget(5)/10).toFixed(1)}}</b> 分还需：</small>
            </q-item-side>
            <q-item-main><small>{{scoreDetail(5)}}</small></q-item-main>
          </q-item>
        </q-collapsible>
      </q-card-main>
    </q-card>

    <div class="row movie" v-if="model.id>0">
      <!-- score rate -->
      <q-card class="col-xs-12 col-md-6" v-if="exactScore>0">
        <q-card-title>评分分布</q-card-title>
        <q-card-separator />
        <q-card-main>
          <v-chart :options="optionsScoreRate" auto-resize ref="chartScoreRate" />
        </q-card-main>
      </q-card>

      <!-- comments -->
      <q-card class="col-xs-12 col-md-6" v-if="changedScores.length>0">
        <q-card-title>评分波动<small>（评分变化前后的数据对比）</small></q-card-title>
        <q-card-separator />
        <q-card-main class="q-pa-none">
          <q-list separator no-border dense>
            <q-item class="my-item-header">
              <q-item-main>时刻</q-item-main>
              <q-item-side>最新评分</q-item-side>
              <q-item-side class="header">
                <div>评分人数增长</div>
                <div class="number">
                  <small>总人数</small>
                  <small>五星</small>
                  <small>四星</small>
                  <small>三星</small>
                  <small>二星</small>
                  <small>一星</small>
                </div>
              </q-item-side>
            </q-item>
            
            <q-item v-for="(item,idx) in changedScores" :key="'s'+item.updateTime">
              <q-item-main>
                <q-item-tile label :class="idx>0?(item.score>item.lastScore?'text-red':'text-green'):''">
                  {{formatTitle(item,idx)}}
                </q-item-tile>
                <q-item-tile sublabel><small>{{formatTime(item.updateTime)}}</small></q-item-tile>
              </q-item-main>
              <q-item-side>{{(item.score/10).toFixed(1)}}</q-item-side>
              <template v-if="idx>0">
                <q-item-side>
                  <div class="number">
                    <small :class="item.ratingCount<item.lastRatingCount?'ex':''">{{item.ratingCount-item.lastRatingCount}}</small>
                    <small :class="formatDelta(item,0)<0?'ex':''">{{formatDelta(item, 0)}}</small>
                    <small :class="formatDelta(item,1)<0?'ex':''">{{formatDelta(item, 1)}}</small>
                    <small :class="formatDelta(item,2)<0?'ex':''">{{formatDelta(item, 2)}}</small>
                    <small :class="formatDelta(item,3)<0?'ex':''">{{formatDelta(item, 3)}}</small>
                    <small :class="formatDelta(item,4)<0?'ex':''">{{formatDelta(item, 4)}}</small>
                  </div>
                </q-item-side>
              </template>
              <template v-else>
                <q-item-side>
                  <div class="number">
                    <small>&nbsp;</small>
                    <small>&nbsp;</small>
                    <small>&nbsp;</small>
                    <small>&nbsp;</small>
                    <small>&nbsp;</small>
                    <small>&nbsp;</small>
                  </div>
                </q-item-side>
              </template>
            </q-item>
          </q-list>
        </q-card-main>
      </q-card>

      <!-- rate trend -->
      <q-card class="col-xs-12 col-md-6" v-if="exactScore>0">
        <q-card-title>分布走势</q-card-title>
        <q-card-separator />
        <q-card-main>
          <v-chart :options="optionsRateTrend" auto-resize ref="chartRateTrend" />
        </q-card-main>
      </q-card>

      <!-- comments -->
      <q-card class="col-xs-12 col-md-6" v-if="comments.length>0">
        <q-card-title>最新评分
          <q-btn-dropdown slot="right" color="primary" dense outline label="下载评论" class="q-py-none">
            <!-- 下拉内容 -->
            <q-list separator class="q-pa-none" style="min-width:120px;">
              <q-item class="q-pa-none">
                <q-btn class="full-width" dense flat v-close-overlay color="black"
                    label="恶意差评(1星)" @click="downloadExcel(1, 1)" />
              </q-item>
              <q-item class="q-pa-none">
                <q-btn class="full-width" dense flat v-close-overlay color="black"
                    label="全部差评(1~2星)" @click="downloadExcel(1, 2)" />
              </q-item>
              <q-item class="q-pa-none">
                <q-btn class="full-width" dense flat v-close-overlay color="primary"
                    label="优质好评(4~5星)" @click="downloadExcel(4, 5)" />
              </q-item>
              <q-item class="q-pa-none">
                <q-btn class="full-width" dense flat v-close-overlay color="primary"
                    label="全部评论" @click="downloadExcel(1, 5)" />
              </q-item>
            </q-list>
          </q-btn-dropdown>
        </q-card-title>
        <q-card-separator />
        <q-card-main class="q-pa-none">
          <q-list separator no-border dense>
            <q-collapsible v-for="(item) in comments" :key="'comment_'+item.userId">
              <template slot="header">
                <q-item-main label>
                  <a :href="'https://movie.douban.com/people/'+item.userId+'/collect'" target="_blank">{{item.userName}}</a>
                  <small>(粉丝:{{item.followers}})</small>
                </q-item-main>
                <q-item-side right v-if="item.rating>0">
                  <q-rating readonly icon="mdi-star" color="primary" v-model="item.rating" :max="item.rating" />
                </q-item-side>
              </template>
              <div>{{item.content}}</div>
            </q-collapsible>
          </q-list>
        </q-card-main>
      </q-card>

      <!-- hot -->
      <q-card class="col-xs-12 col-md-6" v-if="scores.length>0">
        <q-card-title>热度趋势
          <q-btn-toggle slot="right" dense @input="toggleHot" v-model="scoreType" toggle-color="primary"
            :options="[
              {label: '近期走势', value: 'day'},
              {label: '24小时走势', value: 'hour'}
            ]"
          />
        </q-card-title>
        <q-card-separator />
        <q-card-main>
          <v-chart :options="optionsHot" auto-resize ref="chartHot" />
        </q-card-main>
      </q-card>

      <!-- predict -->
      <q-card class="col-xs-12 col-md-6" v-if="model.predict>0 && isAdmin">
        <q-card-title>预测趋势：
          <b class="text-primary">{{(model.predict/10).toFixed(1)}}</b>
          <small v-if="model.predictV4Count>0">（v2:<b>{{(model.predictV4/10).toFixed(1)}}</b>分 | {{model.predictV4Count}}人）</small>
          <small slot="right">（样本：{{model.predictCount}}）</small>
        </q-card-title>
        <q-card-separator />
        <q-card-main>
          <v-chart :options="optionsPredict" auto-resize ref="chartPredict" />          
          <v-chart :options="optionsPredictRate" auto-resize ref="chartPredictRate" style="height:150px;" />
        </q-card-main>
      </q-card>

      <!-- keywords -->
      <q-card class="col-xs-12 col-md-6" v-if="keywords.length>0">
        <q-card-title>豆瓣口碑
          <q-btn-toggle slot="right" v-if="model.score>0"
            dense v-model="keywordType" toggle-color="primary"            
            @input="toggleKeywords"
            :options="[{label:'　全部　',value:'0'},{label:'　好评　',value:'1'},{label:'　差评　',value:'2'}]" />
        </q-card-title>
        <q-card-separator />
        <q-card-main>
          <q-btn v-for="item in keywords" :key="'key_'+item.key" style="margin:0 10px 5px 0"
            outline rounded size="sm" :label="item.key">
            <q-chip floating color="primary">{{item.count}}</q-chip>
          </q-btn>
        </q-card-main>
      </q-card>

      <!-- user profile -->
      <q-card class="col-xs-12 col-md-6">
        <q-card-title>豆瓣用户画像</q-card-title>
        <q-card-separator />
        <q-card-main>
          <v-chart :options="optionsGenderRate" auto-resize ref="chartRateGender" />
          <v-chart :options="optionsAgeRate" auto-resize ref="chartRateAge" style="margin:20px 0" />
          <v-chart :options="optionsTierRate" auto-resize ref="chartRateTier"/>
        </q-card-main>
      </q-card>

      <!-- score profile -->
      <q-card class="col-xs-12 col-md-6" v-if="model.score>0">
        <q-card-title>豆瓣评分偏好</q-card-title>
        <q-card-separator />
        <q-card-main>
          <v-chart :options="optionsGenderScore" auto-resize ref="chartScoreGender" />
          <v-chart :options="optionsAgeScore" auto-resize ref="chartScoreAge" style="margin:20px 0" />
          <v-chart :options="optionsTierScore" auto-resize ref="chartScoreTier" />
        </q-card-main>
      </q-card>
    </div>


    <!-- modal -->
    <q-modal v-if="model.id>0" v-model="setting.modal" :position="$q.platform.is.mobile?'':'right'" :maximized="$q.platform.is.mobile">      
      <q-toolbar color="primary">
        <q-toolbar-title>影片设置</q-toolbar-title>
        <q-btn flat round dense icon="mdi-close" @click="toggleSetting(false)" />
      </q-toolbar>
      <q-list separator no-border>
        <q-list-header>
            影片设置 <label class="float-right text-primary" v-if="model.name">《{{ model.name }}》</label>
        </q-list-header>
        <q-item>
            <q-item-side icon="star" color="red" />
            <q-item-main>
                <q-item-tile label>特别关注</q-item-tile>
                <q-item-tile sublabel>特别关注的影片将出现在影片列表页的[置顶]位置中。</q-item-tile>
            </q-item-main>
            <q-item-side right>
                <q-toggle v-model="setting.checkedTop" color="red" @input="onToggleTop" />
            </q-item-side>
        </q-item>
        <q-item>
            <q-item-side icon="email" color="primary" />
            <q-item-main>
                <q-item-tile label>开分提醒</q-item-tile>
                <q-item-tile sublabel>影片开分或评分发生变化时会进行邮件提醒。</q-item-tile>
            </q-item-main>
            <q-item-side right>
                <q-toggle v-model="setting.checkedMonitor"  @input="onToggleMonitor" />
            </q-item-side>
        </q-item>
        <q-item>
            <q-item-side icon="bar_chart" color="primary" />
            <q-item-main>
                <q-item-tile label>评分跟踪</q-item-tile>
                <q-item-tile sublabel>跟踪影片的评分、想看人数、看过人数等数据的每日变化情况。</q-item-tile>
            </q-item-main>
            <q-item-side right>
                <q-toggle v-model="setting.checkedScore"  @input="onToggleScore"/>
            </q-item-side>
        </q-item>
        <q-item>
            <q-item-side icon="trending_up" color="primary" />
            <q-item-main>
                <q-item-tile label>趋势提醒</q-item-tile>
                <q-item-tile sublabel>针对影片豆瓣评分的变化趋势进行邮件提醒。</q-item-tile>
            </q-item-main>
            <q-item-side right>
                <q-toggle v-model="setting.checkedTrend"  @input="onToggleTrend"/>
            </q-item-side>
        </q-item>
        <q-item>
            <q-item-side icon="bar_chart" color="primary" />
            <q-item-main>
                <q-item-tile label>影评采集</q-item-tile>
                <q-item-tile sublabel>定期采集影片的最新影评数据。</q-item-tile>
            </q-item-main>
            <q-item-side right>
                <q-toggle v-model="setting.checkedReview"  @input="onToggleReview"/>
            </q-item-side>
        </q-item>

        <q-list-header>默认功能 <small>(影评上映期间自动进行)</small></q-list-header>
        <q-item>
            <q-item-side icon="done" color="secondary" />
            <q-item-main>
                <q-item-tile label>评分预测</q-item-tile>
                <q-item-tile sublabel>影片开分前对影片的得分进行预估。</q-item-tile>
            </q-item-main>
            <q-item-side right>
                <q-toggle v-model="setting.dftToggle" disable color="secondary" />
            </q-item-side>
        </q-item>
        <q-item>
            <q-item-side icon="done" color="secondary" />
            <q-item-main>
                <q-item-tile label>用户评论</q-item-tile>
                <q-item-tile sublabel>定期获取影片的用户评论数据。</q-item-tile>
            </q-item-main>
            <q-item-side right>
                <q-toggle v-model="setting.dftToggle" disable color="secondary" />
            </q-item-side>
        </q-item>
        <q-item>
            <q-item-side icon="done" color="secondary" />
            <q-item-main>
                <q-item-tile label>长评短评</q-item-tile>
                <q-item-tile sublabel>定期获取影片的用户短评及影评数据。</q-item-tile>
            </q-item-main>
            <q-item-side right>
                <q-toggle v-model="setting.dftToggle" disable color="secondary" />
            </q-item-side>
        </q-item>
        <q-item>
            <q-item-side icon="done" color="secondary" />
            <q-item-main>
                <q-item-tile label>口碑分析</q-item-tile>
                <q-item-tile sublabel>根据用户长短评进行关键词提取。</q-item-tile>
            </q-item-main>
            <q-item-side right>
                <q-toggle v-model="setting.dftToggle" disable color="secondary" />
            </q-item-side>
        </q-item>
      </q-list>
    </q-modal>
  </q-page>
</template>

<script>
let _tootipRateFormatter = function(param) {
  let str = param.length>0?param[0].name:'';
  for(let i = 0; i < param.length; i++) {
      str = str + '<br/>' 
          + param[i].seriesName + '：' 
          + (param[i].value/10).toFixed(1) + '%';
  }
  return str;
};

let _computeChartOption = function(list, isHour) {
  let size = list.length;
  let labels = [];
  let series1 = [];
  let series2 = [];
  for(let i = 0; i < size; i++) {
    if(isHour) {
      labels.push(list[i].showDate.substring(8,10) + '日' + list[i].showHour + '点');
    } else {
      labels.push(list[i].showDate);
    }
    series1.push(list[i].wishCount);
    series2.push(list[i].ratingCount);    
  }
  let series1Min = Math.floor(list[0].wishCount / 100.0) * 100;
  let series1Max = Math.ceil(list[size-1].wishCount / 100.0) * 100;
  let series2Min = Math.floor(list[0].ratingCount / 100.0) * 100;
  let series2Max = Math.ceil(list[size-1].ratingCount / 100.0) * 100;
  return {
    labels: labels,
    series1: series1,
    series1Interval: (series1Max - series1Min) / 10,
    series1Max: series1Max,
    series1Min: series1Min,
    series2: series2,
    series2Interval: (series2Max - series2Min) / 10,
    series2Max: series2Max,
    series2Min: series2Min
  }
}

const CHART_PREDICT = (predictChart) => ({
  tooltip: {trigger: 'axis',axisPointer:{type :'shadow'}},
  legend: { bottom: 5, data: ['预测得分','样本人数'] },
  grid: { top: '30',left: '10', right: '10', bottom: '30', containLabel: true },
  xAxis: { type: 'category', data: (predictChart?predictChart.labels:[]) },
  yAxis: [
      {
          name: '预测得分',
          type: 'value',
          interval: (predictChart?predictChart.scoreInterval:1),
          min: (predictChart?predictChart.scoreMin:0),
          max: (predictChart?predictChart.scoreMax:10)
      },
      {
          name: '样本人数',
          type: 'value',
          interval: (predictChart?predictChart.ratingCountInterval:100),
          min: (predictChart?predictChart.ratingCountMin:500),
          max: (predictChart?predictChart.ratingCountMax:1500)
      }
  ],
  series: [
      {
          name:'预测得分', type:'line', smooth: true, yAxisIndex: 0,
          data:(predictChart?predictChart.scoreList:[])
      },
      {
          name:'样本人数', type:'line', smooth: true, yAxisIndex: 1,
          data:(predictChart?predictChart.ratingCountList:[])
      }
  ]
});

const CHART_HOT = (predictChart) => ({
  tooltip: {trigger: 'axis',axisPointer:{type :'shadow'}},
  legend: { bottom: 5, data: ['想看人数','评分人数'] },
  grid: { top: '30',left: '10', right: '10', bottom: '30', containLabel: true },
  xAxis: { type: 'category', data: (predictChart?predictChart.labels:[]) },
  yAxis: [
      {
          name: '想看人数',
          type: 'value',
          interval: (predictChart?predictChart.series1Interval:10),
          min: (predictChart?predictChart.series1Min:0),
          max: (predictChart?predictChart.series1Max:100)
      },
      {
          name: '评分人数',
          type: 'value',
          interval: (predictChart?predictChart.series2Interval:10),
          min: (predictChart?predictChart.series2Min:0),
          max: (predictChart?predictChart.series2Max:100)
      }
  ],
  series: [
      {
          name:'想看人数', type:'line', smooth: true, yAxisIndex: 0,
          data:(predictChart?predictChart.series1:[])
      },
      {
          name:'评分人数', type:'line', smooth: true, yAxisIndex: 1,
          data:(predictChart?predictChart.series2:[])
      }
  ]
});

// chart1 : score rate bar chart
const CHART_SCORE_RATE = {
    tooltip : {trigger: 'axis',axisPointer:{type :'shadow'},formatter: _tootipRateFormatter},
    legend: {data:['豆瓣分布', '预测分布']},
    grid: {left: 0,right:'25px',top:'25px',bottom: 0,containLabel: true},
    xAxis : [{ show : false }],
    yAxis : [{data : ['五星','四星','三星','两星','一星'], inverse : true}],
    series : [
        {
            name:'豆瓣分布',
            type:'bar',
            label: {
                show: true,
                position: 'right',
                formatter: function(param){
                    return (param.value/10).toFixed(1) + '%';
                }
            },
            data:[0, 0, 0, 0, 0]
        },
        {
            name:'预测分布',
            type:'bar',
            label: {
                show: true,
                position: 'right',
                formatter: function(param){
                    return (param.value/10).toFixed(1) + '%';
                }
            },
            data:[0, 0, 0, 0, 0]
        }
    ]
};

// chart2 : day score line chart
const CHART_RATE_TREND = {
    tooltip : {trigger: 'axis',axisPointer:{type :'shadow'},formatter: _tootipRateFormatter},
    legend: {data:['五星','四星','三星','两星','一星']},
    grid: {left: 0,right:'5px',top:'55px',bottom: 0,containLabel: true},
    xAxis: {type: 'category',data: []},
    yAxis: {
        type: 'value',
        axisLabel: {
            formatter: function (value) {
                return (value/10).toFixed(1) + '%';
            }
        }
    },
    series: [
        {
            name:'五星',
            type:'line',
            data:[]
        },
        {
            name:'四星',
            type:'line',
            data:[]
        },
        {
            name:'三星',
            type:'line',
            data:[]
        },
        {
            name:'两星',
            type:'line',
            data:[]
        },
        {
            name:'一星',
            type:'line',
            data:[]
        }
    ]
};

// chart3 : predict score rate bar chart
const CHART_PREDICT_RATE = {
    tooltip : {trigger: 'axis',axisPointer:{type :'shadow'},formatter: _tootipRateFormatter},
    legend: {data:['预测评分分布']},
    grid: {left: 0,right:'25px',top:'25px',bottom: 0,containLabel: true},
    xAxis : [{ show : false }],
    yAxis : [{data : ['五星','四星','三星','两星','一星'], inverse : true}],
    series : [
        {
            name:'预测评分分布',
            type:'bar',
            label: {
                show: true,
                position: 'right',
                formatter: function(param){
                    return (param.value/10).toFixed(1) + '%';
                }
            },
            data:[0, 0, 0, 0, 0]
        }
    ]
};

// chart4 : gender rate bar chart
const CHART_GENDER = (_title, _data) => ({
  title: {text: '性别分布'},
  tooltip : {trigger: 'axis',axisPointer:{type :'shadow'},formatter: _tootipRateFormatter},
  legend: {top:'25px',data:[_title?_title:'本片豆瓣用户', '豆瓣整体用户', '电影市场整体']},
  grid: {left: 0,right:0,top:'60px',bottom: 0,containLabel: true},
  yAxis : [{ show : false }],
  xAxis : [{data : ['男性', '女性']}],
  series : [
      {
          name:_title?_title:'本片豆瓣用户',
          type:'bar',
          label: {
              show: true,
              position: 'top',
              formatter: function(param){
                  return (param.value/10).toFixed(1) + '%';
              }
          },
          data:_data?_data:[0, 0]
      },
      {
          name:'豆瓣整体用户',
          type:'bar',
          label: {
              show: false,
              position: 'top',
              formatter: function(param){
                  return (param.value/10).toFixed(1) + '%';
              }
          },
          data:[400, 600]
      },
      {
          name:'电影市场整体',
          type:'bar',
          label: {
              show: false,
              position: 'top',
              formatter: function(param){
                  return (param.value/10).toFixed(1) + '%';
              }
          },
          data:[450, 550]
      }
  ]
});

// chart5 : age rate bar chart
const CHART_AGE = (_title, _data) => ({
  title: {text: '年龄分布'},
  tooltip : {trigger: 'axis',axisPointer:{type :'shadow'},formatter: _tootipRateFormatter},
  legend: {top:'25px',data:[_title?_title:'本片豆瓣用户', '豆瓣整体用户', '电影市场整体']},
  grid: {left: 0,right:0,top:'60px',bottom: 0,containLabel: true},
  yAxis : [{ show : false }],
  xAxis : [{data : ['19岁及以下', '20~24岁', '25~29岁', '30~39岁', '40岁及以上']}],
  series : [
      {
          name:_title?_title:'本片豆瓣用户',
          type:'bar',
          label: {
              show: true,
              position: 'top',
              formatter: function(param){
                  return (param.value/10).toFixed(1) + '%';
              }
          },
          data:_data?_data:[0, 0, 0, 0, 0]
      },
      {
          name:'豆瓣整体用户',
          type:'bar',
          label: {
              show: false,
              position: 'top',
              formatter: function(param){
                  return (param.value/10).toFixed(1) + '%';
              }
          },
          data:[50, 270, 470, 200, 20]
      },
      {
          name:'电影市场整体',
          type:'bar',
          label: {
              show: false,
              position: 'top',
              formatter: function(param){
                  return (param.value/10).toFixed(1) + '%';
              }
          },
          data:[30, 310, 260, 290, 110]
      }
  ]
});

// chart6 : tier rate bar chart
const CHART_TIER = (_title, _data) => ({
  title: {text: '城市分布'},
  tooltip : {trigger: 'axis',axisPointer:{type :'shadow'},formatter: _tootipRateFormatter},
  legend: {top:'25px',data:[_title?_title:'本片豆瓣用户', '豆瓣整体用户', '电影市场整体']},
  grid: {left: 0,right:0,top:'60px',bottom: 0,containLabel: true},
  yAxis : [{ show : false }],
  xAxis : [{data : ['一线城市', '二线城市', '三线及以下城市']}],
  series : [
      {
          name:_title?_title:'本片豆瓣用户',
          type:'bar',
          label: {
              show: true,
              position: 'top',
              formatter: function(param){
                  return (param.value/10).toFixed(1) + '%';
              }
          },
          data:_data?_data:[0, 0, 0]
      },
      {
          name:'豆瓣整体用户',
          type:'bar',
          label: {
              show: false,
              position: 'top',
              formatter: function(param){
                  return (param.value/10).toFixed(1) + '%';
              }
          },
          data:[350, 430, 220]
      },
      {
          name:'电影市场整体',
          type:'bar',
          label: {
              show: false,
              position: 'top',
              formatter: function(param){
                  return (param.value/10).toFixed(1) + '%';
              }
          },
          data:[150, 410, 440]
      }
  ]
});

// chart7 : predict score rate bar chart
const CHART_GENDER_SCORE = {
    title: {text: '男/女'},
    tooltip : {trigger: 'axis',axisPointer:{type :'shadow'}},
    legend: {data:['评分']},
    grid: {left: 0,right:0,top:'25px',bottom: 0,containLabel: true},
    yAxis : [{ show : false }],
    xAxis : [{data : ['男性','女性','全部']}],
    series : [
        {
            name:'评分',
            type:'bar',
            label: { show: true,position: 'top'},
            data:[0, 0, 0]
        }
    ]
};

// chart8 : predict score rate bar chart
const CHART_AGE_SCORE = {
    title: {text: '各年龄段'},
    tooltip : {trigger: 'axis',axisPointer:{type :'shadow'}},
    legend: {data:['评分']},
    grid: {left: 0,right:0,top:'25px',bottom: 0,containLabel: true},
    yAxis : [{ show : false }],
    xAxis : [{data : ['19岁及以下', '20~24岁', '25~29岁', '30~39岁', '40岁及以上', '全部']}],
    series : [
        {
            name:'评分',
            type:'bar',
            label: { show: true,position: 'top'},
            data:[0, 0, 0, 0, 0, 0]
        }
    ]
};

// chart8 : predict score rate bar chart
const CHART_TIER_SCORE = {
    title: {text: '各线城市'},
    tooltip : {trigger: 'axis',axisPointer:{type :'shadow'}},
    legend: {data:['评分']},
    grid: {left: 0,right:0,top:'25px',bottom: 0,containLabel: true},
    yAxis : [{ show : false }],
    xAxis : [{data : ['一线', '二线', '三线及以下', '全部']}],
    series : [
        {
            name:'评分',
            type:'bar',
            label: { show: true,position: 'top'},
            data:[0, 0, 0, 0]
        }
    ]
};


export default {
  name: 'PageMovieMain',
  data() {
    return {
      isAdmin: this.$api.account.isAdmin(),
      changedScores:[],
      comments:[],
      hourScores:[],
      scores:[],
      keywords:[],
      keywordType: '0',
      scoreRates:[0,0,0,0,0],
      scoreType: 'day',
      model: {id:0},
      setting:{
        modal: false,
        dftToggle: true,
        checkedTop: false,
        checkedMonitor: false,
        checkedScore: false,
        checkedTrend: false,
        checkedReview: false
      },

      // charts
      optionsPredict: CHART_PREDICT(false),
      optionsHot: CHART_HOT(false),
      optionsScoreRate: CHART_SCORE_RATE,
      optionsRateTrend: CHART_RATE_TREND,
      optionsPredictRate: CHART_PREDICT_RATE,
      optionsGenderRate: CHART_GENDER(false, false),
      optionsAgeRate: CHART_AGE(false, false),
      optionsTierRate: CHART_TIER(false, false),
      optionsGenderScore: CHART_GENDER_SCORE,
      optionsAgeScore: CHART_AGE_SCORE,
      optionsTierScore: CHART_TIER_SCORE,
    }
  },
  mounted() {
    // ui
    let me = this;
    this.$api.ui.pageTitle = '豆瓣影片';
    this.$api.ui.pageBackBtn = function(){
      me.$router.push('/movie');
    }

    if(this.$route.query.setting=='true') {
      this.toggleSetting(true);
    }
    this.loadUserRatings();
    this.loadMovieScoresChanged();
    this.loadMovieComments();
    // this.loadMovieScores(false);
    this.toggleKeywords();
  },
  methods: {
    downloadExcel(min, max) {
      let me = this;
      let filename = '《' + me.model.name + '》评论表.xls';
      this.$api.movie.downloadComments(me.model.id, min, max, filename);
    },
    loadMovieComments() {
      let me = this;
      let id = this.$route.params.id;
      let offset = 0;
      this.$api.movie.loadComments(id, offset, res => {
        me.comments = res.data.model;
      });
    },
    toggleKeywords() {
      let me = this;
      let id = this.$route.params.id;
      let min = 0;
      let max = 5;
      if(me.model.score > 0) {
        if(me.keywordType == '0') {
          min = 1; max = 5;
        } else if(me.keywordType == '1') {
          min = 4; max = 5;
        } else if(me.keywordType == '2') {
          min = 1; max = 2;
        }
      }
      me.$api.movie.loadKeywords(id, min, max, res=>{
        me.keywords = res.data;
      });
    },
    // ajax load
    loadUserRatings() {
      let me = this;
      let id = this.$route.params.id;
      this.$api.movie.loadUserRatings(id, res => {
        let data = res.data.model;
        me.$api.ui.pageTitle = data.name;
        me.model = data;
        me.setting.checkedTop = (data.marks.indexOf('TOP') >= 0);
        me.setting.checkedMonitor = (data.marks.indexOf('MONITOR') >= 0);
        me.setting.checkedScore = (data.marks.indexOf('SCORE') >= 0);
        me.setting.checkedTrend = (data.marks.indexOf('TREND') >= 0);
        me.setting.checkedReview = (data.marks.indexOf('REVIEW') >= 0);
        me.optionsScoreRate.series[1].data = data.predictStarRates;

        // 预测数据
        me.optionsPredict = CHART_PREDICT(data.predictChart);
        me.optionsPredictRate.series[0].data = data.predictStarRates;

        // 性别分布: [0]男,[1]女
        let genderTotalCounts = data.genderUserCounts[0] + data.genderUserCounts[1];
        if(genderTotalCounts > 0) {
          me.optionsGenderRate.series[0].data = [
            1000*data.genderUserCounts[0]/genderTotalCounts,
            1000*data.genderUserCounts[1]/genderTotalCounts,
          ];
        }
        // age
        let ageTotalCounts = 0;
        data.ageUserCounts.forEach((item)=>{ageTotalCounts+=item});
        if(ageTotalCounts > 0) {
          me.optionsAgeRate.series[0].data = [
            1000*data.ageUserCounts[0]/ageTotalCounts,
            1000*data.ageUserCounts[1]/ageTotalCounts,
            1000*data.ageUserCounts[2]/ageTotalCounts,
            1000*(data.ageUserCounts[3]+data.ageUserCounts[4])/ageTotalCounts,
            1000*data.ageUserCounts[5]/ageTotalCounts,
          ];
        }
        // tier
        let tierTotalCounts = 0;
        data.tierUserCounts.forEach((item)=>{tierTotalCounts+=item});
        if(tierTotalCounts > 0) {
          me.optionsTierRate.series[0].data = [
            1000*data.tierUserCounts[0]/tierTotalCounts,
            1000*data.tierUserCounts[1]/tierTotalCounts,
            1000*(data.tierUserCounts[2]+data.tierUserCounts[3]+data.tierUserCounts[4])/tierTotalCounts
          ];
        }

        // 评分趋势
        let list = data.scoreList;
        me.scores = list;
        if(list.length > 0) {
          me.scoreRates = list[list.length - 1].starRates;
          me.optionsScoreRate.series[0].data = me.scoreRates;
          // 绑定趋势图
          CHART_RATE_TREND.xAxis.data = [];
          for(let j = 0; j < 5; j++) {
            CHART_RATE_TREND.series[j].data = [];
          }
          let startIndex = list.length > 14 ? list.length - 14 : 0;
          for(let i = startIndex; i < list.length; i++) {
            let item = list[i];
            CHART_RATE_TREND.xAxis.data.push(item.showDate);
            for(let j = 0; j < 5; j++) {
              CHART_RATE_TREND.series[j].data.push(item.starRates[j]);  
            }
          }
          // 绑定热度趋势
          me.optionsHot = CHART_HOT(_computeChartOption(list, false));
        }

        // 评分偏好
        let doubanScore = (data.score / 10.0).toFixed(1);
        me.optionsGenderScore.series[0].data = data.genderRatings;
        me.optionsGenderScore.series[0].data[2] = doubanScore;

        me.optionsAgeScore.series[0].data = data.ageRatings;
        me.optionsAgeScore.series[0].data[5] = doubanScore;

        me.optionsTierScore.series[0].data = data.tierRatings;
        me.optionsTierScore.series[0].data[3] = doubanScore;

      });
    },
    loadMovieScoresChanged() {
      let me = this;
      let id = this.$route.params.id;
      this.$api.movie.loadScoresChanged(id, res => {
        me.changedScores = res.data.model;
      });
    },
    loadMovieScores(isHour) {
      let me = this;
      let id = this.$route.params.id;
      if(isHour) {
        if(me.hourScores.length>0) {
          me.optionsHot = CHART_HOT(_computeChartOption(me.hourScores, true));
          return;
        };
        this.$api.movie.loadScoresByHour(id, res=>{
          let list = res.data.model;
          me.hourScores = list;
          if(list.length > 0) {
            // 绑定热度趋势
            me.optionsHot = CHART_HOT(_computeChartOption(list, true));
          }
        });
      } else {
        if(me.scores.length>0) {
          me.optionsHot = CHART_HOT(_computeChartOption(me.scores, false));
          return;
        };
        this.$api.movie.loadScoresByDate(id, res => {
          let list = res.data.model;
          me.scores = list;
          if(list.length > 0) {
            me.scoreRates = list[list.length - 1].starRates;
            me.optionsScoreRate.series[0].data = me.scoreRates;
            // 绑定趋势图
            let startIndex = list.length > 14 ? list.length - 14 : 0;
            for(let i = startIndex; i < list.length; i++) {
              let item = list[i];
              CHART_RATE_TREND.xAxis.data.push(item.showDate);
              for(let j = 0; j < 5; j++) {
                CHART_RATE_TREND.series[j].data.push(item.starRates[j]);  
              }
            }
            // 绑定热度趋势
            me.optionsHot = CHART_HOT(_computeChartOption(list));
          }
        });
      }
    },
    toggleHot(val) {
      this.loadMovieScores(val == 'hour');
    },

    // ========= settings
    toggleSetting(open) {
      this.setting.modal = open;
    },
    onToggleChange(val, type) {
      this.$api.movie.doMarks(this.$route.params.id, type, val);
    },
    onToggleTop(val) {
      return this.onToggleChange(val, 'TOP');
    },
    onToggleMonitor(val) {
      return this.onToggleChange(val, 'MONITOR');
    },
    onToggleScore(val) {
      return this.onToggleChange(val, 'SCORE');
    },
    onToggleTrend(val) {
      return this.onToggleChange(val, 'TREND');
    },
    onToggleReview(val) {
        return this.onToggleChange(val, 'REVIEW');
    },

    // ========= score delta
    scoreTarget(delta) {
      return Math.round(this.exactScore) + delta - 0.49;
    },

    scoreDetail(delta) {
      let curScore = this.exactScore;
      let tarScore = Math.round(curScore) + delta - 0.49;
      let detail = '';
      let star5Num = this.scoreNum(tarScore, curScore, this.model.ratingCount, 100);      
      if(star5Num > 0) {
        detail += '五星 ('+star5Num+')';
      }
      let star4Num = this.scoreNum(tarScore, curScore, this.model.ratingCount, 80);
      if(star4Num > 0) {
        detail += ' / 四星 ('+star4Num+')';
      }
      return detail;
    },

    scoreNum(tarScore, curScore, rCount, starScore) {
      if(starScore - tarScore < 1 || rCount <= 0) {
        return 0;
      }
      return Math.round((tarScore - curScore) * rCount / (starScore - tarScore));
    },
    
    formatDelta(item, starIndex) {
      return Math.round(
                (item.ratingCount * item.starRates[starIndex]
                    - item.lastRatingCount * item.lastStarRates[starIndex])
                / 1000
            );    
    },
    formatTime(time) {
      return time.substring(5,16)//.replace('-','月').replace(' ','日').replace(':','点')+'分';
    },
    formatTitle(item,idx) {
      if(idx == 0) {
        return '首次开分';
      }
      if(item.score > item.lastScore) {
        return '上涨↑' + ((item.score-item.lastScore)/10).toFixed(1);
      } else {
        return '下跌↓' + ((item.lastScore-item.score)/10).toFixed(1);
      }
    }
  },
  computed: {
    exactScore() {
      let num = 0;
      for(let i = 0; i < 5; i++) {
        num += (10-2*i) * this.scoreRates[i];
      }
      return (num / 100);
    },
    score() {
      return this.exactScore > 0 ? this.exactScore : this.model.score;
    }
  }
}
</script>

<style>
span.relative-position {
  padding: 0 10px;
}
.echarts {
  width: 100%;
  height: 300px;
}

.movie .q-card {
  margin-bottom:10px;
}

.movie .q-card-primary {
  padding: 5px 16px;
}

.movie .q-card-separator {
  border-top: 1px dashed #ccc;
  background:none;
  height:0;
}

.score-target .q-collapsible-sub-item {
  padding:0;  
}
</style>

